package com.example.cloud.util;

import com.example.cloud.entity.User;
import com.example.cloud.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Slf4j
@Component
@RequiredArgsConstructor
public class DataGenerator {
    
    private final UserMapper userMapper;
    private final BatchInsertUtil batchInsertUtil;
    private final JdbcTemplate jdbcTemplate;
    private final Random random = new Random();
    
    // 姓氏列表
    private static final String[] SURNAMES = {"张", "王", "李", "赵", "刘", "陈", "杨", "黄", "周", "吴"};
    // 名字列表
    private static final String[] NAMES = {"伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "洋"};
    // 邮箱域名列表
    private static final String[] EMAIL_DOMAINS = {"gmail.com", "yahoo.com", "hotmail.com", "outlook.com", "qq.com"};
    
    /**
     * 生成随机用户名
     */
    private String generateUsername() {
        // 使用UUID的一部分来确保唯一性
        String uuid = UUID.randomUUID().toString().substring(0, 8);
        return SURNAMES[random.nextInt(SURNAMES.length)] + 
               NAMES[random.nextInt(NAMES.length)] + 
               random.nextInt(10000) + // 增加数字范围
               uuid.substring(0, 4); // 添加UUID的一部分
    }
    
    /**
     * 生成随机邮箱
     */
    private String generateEmail(String username) {
        return username.toLowerCase() + "@" + EMAIL_DOMAINS[random.nextInt(EMAIL_DOMAINS.length)];
    }
    
    /**
     * 生成随机年龄
     */
    private Integer generateAge() {
        return 18 + random.nextInt(43); // 18-60岁
    }
    
    /**
     * 批量生成用户数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void generateUsers(int count) {
        log.info("开始生成{}条用户数据", count);
        long startTime = System.currentTimeMillis();
        
        try {
            // 使用原生SQL批量插入，性能更好
            String sql = "INSERT INTO user (username, email, age, create_time, update_time) VALUES (?, ?, ?, NOW(), NOW())";
            List<Object[]> batchArgs = new ArrayList<>(1000);
            
            for (int i = 0; i < count; i++) {
                String username = generateUsername();
                String email = generateEmail(username);
                Integer age = generateAge();
                
                Object[] args = new Object[] {username, email, age};
                batchArgs.add(args);
                
                // 每1000条数据批量插入一次
                if (batchArgs.size() >= 1000) {
                    batchInsertUtil.batchUpdate(sql, batchArgs);
                    batchArgs.clear();
                }
            }
            
            // 插入剩余数据
            if (!batchArgs.isEmpty()) {
                batchInsertUtil.batchUpdate(sql, batchArgs);
            }
            
            long endTime = System.currentTimeMillis();
            log.info("数据生成完成，共生成{}条数据，总耗时{}毫秒", count, (endTime - startTime));
        } catch (Exception e) {
            log.error("数据生成过程发生错误", e);
            throw new RuntimeException("数据生成失败", e);
        }
    }
    
    /**
     * 使用命名参数批量插入用户数据（适用于复杂对象）
     */
    @Transactional(rollbackFor = Exception.class)
    public void generateUsersWithNamedParams(int count) {
        log.info("开始生成{}条用户数据（命名参数方式）", count);
        long startTime = System.currentTimeMillis();
        
        try {
            String sql = "INSERT INTO user (username, email, age, create_time, update_time) " +
                         "VALUES (:username, :email, :age, NOW(), NOW())";
            
            List<Map<String, Object>> batchValues = new ArrayList<>(1000);
            
            for (int i = 0; i < count; i++) {
                String username = generateUsername();
                String email = generateEmail(username);
                Integer age = generateAge();
                
                Map<String, Object> params = new HashMap<>();
                params.put("username", username);
                params.put("email", email);
                params.put("age", age);
                
                batchValues.add(params);
                
                // 每1000条数据批量插入一次
                if (batchValues.size() >= 1000) {
                    batchInsertUtil.batchUpdateWithMap(sql, batchValues);
                    batchValues.clear();
                }
            }
            
            // 插入剩余数据
            if (!batchValues.isEmpty()) {
                batchInsertUtil.batchUpdateWithMap(sql, batchValues);
            }
            
            long endTime = System.currentTimeMillis();
            log.info("数据生成完成，共生成{}条数据，总耗时{}毫秒", count, (endTime - startTime));
        } catch (Exception e) {
            log.error("数据生成过程发生错误", e);
            throw new RuntimeException("数据生成失败", e);
        }
    }
} 